package com.ruite.livepad;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.ruite.livepad.service.DownloadIntentService;
import com.ruite.livepad.util.DownloadUtils;
import com.ruite.livepad.util.NotificationsUtils;
import com.ruite.livepad.util.UpdateInfo;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zero.cdownload.CDownload;
import com.zero.cdownload.config.CDownloadConfig;
import com.zero.cdownload.config.ConnectConfig;
import com.zero.cdownload.config.ThreadPoolConfig;
import com.zero.cdownload.listener.CDownloadListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity {
    private String webUrl = "http://192.168.11.100/index";
    //    private String webUrl = "http://192.168.1.222";
    private static final int SUCCESS = 100;
    private static final int FAIL = 101;
    private static final int EXIST = 102;
    //    private String webUrl = "http://172.31.3.73:8080";
    private WebView wvBookPlay;
    private FrameLayout flVideoContainer;
    ProgressBar progressBar;
    RxPermissions rxPermissions;
    File photoFile = null;

    private ValueCallback<Uri[]> mFilePathCallback = null;
    private int REQUEST_CODE_LOLIPOP = 1;  // 5.0以上版本
    private String mCameraPhotoPath = null;  // 拍照的图片路径

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    Toast.makeText(MainActivity.this, "文件下载成功！", Toast.LENGTH_LONG).show();
                    break;
                case FAIL:
                    Toast.makeText(MainActivity.this, "文件下载失败！", Toast.LENGTH_LONG).show();
                    break;
                case EXIST:
                    Toast.makeText(MainActivity.this, "文件已经存在！", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };


    private ImageView iv_logo;
//    private ImageView iv_left_fly;
//    private ImageView iv_right_fly;
//    private LinearLayout ll_splash;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CDownloadConfig downloadConfig = CDownloadConfig.build()
                .setDiskCachePath("/sdcard/Download")
                .setConnectConfig(ConnectConfig.build().setConnectTimeOut(10000).setReadTimeOut(20000))
                .setIoThreadPoolConfig(ThreadPoolConfig.build().setCorePoolSize(4).setMaximumPoolSize(100).setKeepAliveTime(60));
        CDownload.getInstance().init(downloadConfig);
        rxPermissions = new RxPermissions(this);
//        ll_splash = findViewById(R.id.ll_splash);
        iv_logo = findViewById(R.id.iv_logo);
//        iv_left_fly = findViewById(R.id.iv_left_fly);
//        iv_right_fly = findViewById(R.id.iv_right_fly);
        wvBookPlay = findViewById(R.id.webview);
        progressBar = findViewById(R.id.progressBar);
        flVideoContainer = findViewById(R.id.flVideoContainer);
        wvBookPlay.setWebViewClient(new WebViewClient() {
            // Load opened URL in the application instead of standard browser
            // application
            public void onPageCommitVisible(WebView view, String url) {
                if (url.startsWith("http://192.168.11.100:5004") || url.startsWith("http://192.168.11.100:8788") || url.startsWith("http://192.168.11.100:3000")) {
                    setScreenLandscape();
                } else {
                    if (url.startsWith("http://192.168.11.100:9999/cas") && (url.contains("5004") || url.contains("8788") || url.contains("3000"))) {
                        setScreenLandscape();
                    } else {
                        setScreenPortrait();
                    }
                }
            }

            public boolean shouldOverrideUrlLoading(WebView view, final String url) {
//                if (url.startsWith("http://192.168.11.100:5004") || url.startsWith("http://192.168.11.100:8788") || url.startsWith("http://192.168.11.100:3000")) {
//                    setScreenLandscape();
//                } else {
//                    if (url.startsWith("http://192.168.11.100:9999/cas") && (url.contains("5004") || url.contains("8788") || url.contains("3000"))) {
//                        setScreenLandscape();
//                    } else {
//                        setScreenPortrait();
//                    }
//                }
                if (url.endsWith(".mp4") || (url.endsWith(".MP4"))) {
                    rxPermissions
                            .request(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                String fileId = "100";
                                String fileName = wvBookPlay.getTitle() + ".mp4";
                                String destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                        .getAbsolutePath() + File.separator + fileName;
                                Intent intent = new Intent(MainActivity.this, DownloadIntentService.class);
                                intent.setAction(DownloadIntentService.ACTION_VIDEO);
                                intent.putExtra(DownloadIntentService.EXTRA_FILENAME, destPath);
                                try {
                                    fileId = url.substring(url.lastIndexOf('/') + 1, url.length() - 4);
                                    intent.putExtra(DownloadIntentService.EXTRA_NOTIFICATIONID, Integer.parseInt(fileId));
                                } catch (Exception e) {

                                }
                                intent.putExtra(DownloadIntentService.EXTRA_URL, url);
                                MainActivity.this.startService(intent);
                            } else {
                                Toast.makeText(MainActivity.this, "没有存储权限，请在设置里设置权限！", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                } else if (url.endsWith(".mp3") || (url.endsWith(".MP3"))) {
                    rxPermissions
                            .request(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                String fileId = url.substring(url.lastIndexOf('/'), url.length());
                                String fileName = wvBookPlay.getTitle() + ".mp3";
                                String destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                        .getAbsolutePath() + File.separator + fileName;
                                Intent intent = new Intent(MainActivity.this, DownloadIntentService.class);
                                intent.setAction(DownloadIntentService.ACTION_MUSIC);
                                intent.putExtra(DownloadIntentService.EXTRA_FILENAME, destPath);
                                intent.putExtra(DownloadIntentService.EXTRA_URL, url);
                                try {
                                    intent.putExtra(DownloadIntentService.EXTRA_NOTIFICATIONID, Integer.parseInt(fileId));
                                } catch (Exception e) {

                                }
                                MainActivity.this.startService(intent);
                            } else {
                                Toast.makeText(MainActivity.this, "没有存储权限，请在设置里设置权限！", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                } else if (url.contains("/gamefile/download?id=")) {
                    //游戏下载
                    rxPermissions
                            .request(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                String fileId = "100";
                                String fileName = wvBookPlay.getTitle();
                                String destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                        .getAbsolutePath() + File.separator + fileName;
                                Intent intent = new Intent(MainActivity.this, DownloadIntentService.class);
                                intent.setAction(DownloadIntentService.ACTION_VIDEO);
                                intent.putExtra(DownloadIntentService.EXTRA_FILENAME, destPath);
                                try {
                                    fileId = url.substring(url.lastIndexOf('/') + 1, url.length() - 4);
                                    intent.putExtra(DownloadIntentService.EXTRA_NOTIFICATIONID, Integer.parseInt(fileId));
                                } catch (Exception e) {

                                }
                                intent.putExtra(DownloadIntentService.EXTRA_URL, url);
                                MainActivity.this.startService(intent);
                            } else {
                                Toast.makeText(MainActivity.this, "没有存储权限，请在设置里设置权限！", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                } else {
                    view.loadUrl(url);
                }
                return true;
            }

        });

        wvBookPlay.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimeType, long contentLength) {
                //下载图书链接 http://172.31.3.73:8080/live/download/13626?bookId=583
                if (url.contains("/live/download/")) {
                    rxPermissions.request(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                final String fileName = wvBookPlay.getTitle() + ".txt";
                                final String destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                        .getAbsolutePath() + File.separator + fileName;
                                new Thread() {
                                    @Override
                                    public void run() {
                                        try {
                                            URL u = new URL(url);
                                            //打开连接
                                            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                                            conn.setRequestMethod("GET");
                                            conn.setRequestProperty("X-Online-Host", u.getHost());
                                            // conn.setRequestProperty("Accept", ACCEPT);
                                            conn.setRequestProperty("Accept-Language", "zh-CN");
//                                            conn.setRequestProperty("Referer", u.toString());
                                            conn.setRequestProperty("Charset", "UTF-8");
                                            // conn.setRequestProperty("User-Agent", USERAGENT);
                                            conn.setRequestProperty("Connection", "Keep-Alive");
                                            conn.setConnectTimeout(5000);
                                            conn.setReadTimeout(5000);
                                            conn.connect();
                                            int code = conn.getResponseCode();
                                            if (code == 200) {
                                                //打开输入流
                                                InputStream is = conn.getInputStream();
                                                //获得长度
                                                int contentLength = conn.getContentLength();
                                                //下载后的文件名
                                                File file1 = new File(destPath);
                                                if (file1.exists()) {
                                                    handler.sendEmptyMessage(EXIST);
                                                } else {
                                                    //创建字节流
                                                    byte[] bs = new byte[1024];
                                                    int len;
                                                    OutputStream os = new FileOutputStream(file1);
                                                    //写数据
                                                    while ((len = is.read(bs)) != -1) {
                                                        os.write(bs, 0, len);
                                                    }
                                                    //完成后关闭流
                                                    os.close();
                                                    is.close();
                                                    handler.sendEmptyMessage(SUCCESS);
                                                }
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            handler.sendEmptyMessage(FAIL);
                                        }
                                    }
                                }.start();
//                                Intent intent = new Intent(MainActivity.this, DownloadIntentService.class);
//                                intent.setAction(DownloadIntentService.ACTION_VIDEO);
//                                intent.putExtra(DownloadIntentService.EXTRA_FILENAME, fileName);
//                                intent.putExtra(DownloadIntentService.EXTRA_URL, url);
//                                MainActivity.this.startService(intent);
                            } else {
                                Toast.makeText(MainActivity.this, "没有存储权限，请在设置里设置权限！", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            }
        });

        // Enable some feature like Javascript and pinch zoom
        WebSettings websettings = wvBookPlay.getSettings();
        websettings.setJavaScriptEnabled(true);     // Warning! You can have XSS vulnerabilities!
        websettings.setJavaScriptCanOpenWindowsAutomatically(true);
        websettings.setUseWideViewPort(true);     // Warning! You can have XSS vulnerabilities!
        websettings.setLoadWithOverviewMode(true);     // Warning! You can have XSS vulnerabilities!
        websettings.setAllowFileAccess(true);
        //可以使用localStorage
        websettings.setDomStorageEnabled(true);
        //可以有数据库
        websettings.setDatabaseEnabled(true);
        //可以有缓存
        websettings.setAppCacheEnabled(true);

        //设置自适应屏幕，两者合用
        websettings.setUseWideViewPort(true);   //将图片调整到合适的大小
        websettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        websettings.setSupportZoom(true);
        websettings.setBuiltInZoomControls(false);
        websettings.setJavaScriptCanOpenWindowsAutomatically(true);

        websettings.setSaveFormData(true);    //设置webview保存表单数据
        websettings.setSavePassword(true);    //设置webview保存密码

        try {
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = websettings.getClass();
                Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(websettings, true);
                }
            }
        } catch (Exception e) {
        }
        websettings.setPluginState(WebSettings.PluginState.ON);
        wvBookPlay.setWebChromeClient(new MyWebChromeClient() {
            // Set progress bar during loading
            public void onProgressChanged(WebView view, int progress) {
                if (progress == 100) {
                    progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(progress);//设置进度值
                }
                super.onProgressChanged(view, progress);
            }


            // 5.0+
            @Override
            public boolean onShowFileChooser(WebView webView, final ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                rxPermissions
                        .request(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA
                        ).subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            if (mFilePathCallback != null) {
                                mFilePathCallback.onReceiveValue(null);
                            }
                            mFilePathCallback = filePathCallback;
                            Intent intent = gotoChooseFile();  // 选择文件及拍照
                            startActivityForResult(intent, REQUEST_CODE_LOLIPOP);
                        } else {
                            Toast.makeText(MainActivity.this, "没有存储权限，请在设置里设置权限！", Toast.LENGTH_LONG).show();
                        }
                    }
                });
                return true;
            }

            // 4.1+
            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {

            }

        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            websettings.setMixedContentMode(websettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        CookieManager cookieManager = CookieManager.getInstance();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("android");
        cookieManager.setCookie(webUrl, stringBuffer.toString());
        cookieManager.setAcceptCookie(true);
        wvBookPlay.loadUrl(webUrl);

        //检测是否有版本更新
        new Thread() {
            @Override
            public void run() {
                UpdateInfo.CheckVersion(MainActivity.this);// 检查更新
            }
        }.start();

        NotificationsUtils.showDialog(this);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        switch (newConfig.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (wvBookPlay.canGoBack()) {
            wvBookPlay.goBack();
            String url = wvBookPlay.getOriginalUrl();
            if (url.startsWith("http://192.168.11.100:5004") || url.startsWith("http://192.168.11.100:8788") || url.startsWith("http://192.168.11.100:3000")) {
                setScreenLandscape();
            } else {
                if (url.startsWith("http://192.168.11.100:9999/cas") && (url.contains("5004") || url.contains("8788") || url.contains("3000"))) {
                    setScreenLandscape();
                } else {
                    setScreenPortrait();
                }
            }
        } else {
            finish();
        }
    }

    class MyWebChromeClient extends WebChromeClient {
        WebChromeClient.CustomViewCallback mCallback;

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            fullScreen();
            wvBookPlay.setVisibility(View.GONE);
            flVideoContainer.setVisibility(View.VISIBLE);
            flVideoContainer.addView(view);
            mCallback = callback;
            super.onShowCustomView(view, callback);
        }

        @Override
        public void onHideCustomView() {
            fullScreen();
            wvBookPlay.setVisibility(View.VISIBLE);
            flVideoContainer.setVisibility(View.GONE);
            flVideoContainer.removeAllViews();
            super.onHideCustomView();
        }
    }

    private void fullScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    private void setScreenPortrait() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    private void setScreenLandscape() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    protected void onDestroy() {
//        removeCookie(this);
        if (wvBookPlay != null) {
            wvBookPlay.removeAllViews();
            wvBookPlay.destroy();
        }
        super.onDestroy();
    }

    private void removeCookie(Context context) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 通过浏览器下载
     *
     * @param url
     */
    private void downloadyBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    private void downloadBySystem(String url, String contentDisposition, String mineType) {
        //指定下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //允许媒体扫描，根据下载的文件类型被加入相册，音乐等媒体库
        request.allowScanningByMediaScanner();
        //设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //设置通知标题
        request.setTitle("下载");
        request.setDescription("文件下载");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            request.setAllowedOverMetered(false);
        }
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setAllowedOverRoaming(true);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        String fileName = URLUtil.guessFileName(url, contentDisposition, mineType);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setVisibleInDownloadsUi(true);
        final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        long downloaded = downloadManager.enqueue(request);
    }


    private class DownloadTask extends AsyncTask<String, Void, Void> {
        // 传递两个参数：URL 和 目标路径
        private String url;
        private String destPath;
        private boolean success;

        @Override
        protected void onPreExecute() {
//            log.info("开始下载");
            Toast.makeText(MainActivity.this, "开始下载...", Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(String... params) {
//            log.debug("doInBackground. url:{}, dest:{}", params[0], params[1]);
            url = params[0];
            destPath = params[1];
            OutputStream out = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(15000);
                urlConnection.setReadTimeout(15000);
                InputStream in = urlConnection.getInputStream();
                out = new FileOutputStream(params[1]);
                byte[] buffer = new byte[10 * 1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                in.close();
                success = true;
            } catch (IOException e) {
                e.printStackTrace();
                success = false;
//                log.warn(e);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
//                        log.warn(e);
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (success) {
                Toast.makeText(MainActivity.this, "完成下载！", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "下载失败！", Toast.LENGTH_LONG).show();
            }
//            log.info("完成下载");

//            Intent handlerIntent = new Intent(Intent.ACTION_VIEW);
//            String mimeType = getMIMEType(url);
//            Uri uri = Uri.fromFile(new File(destPath));
////            log.debug("mimiType:{}, uri:{}", mimeType, uri);
//            handlerIntent.setDataAndType(uri, mimeType);
//            startActivity(handlerIntent);
        }

        private String getMIMEType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
//            log.debug("extension:{}", extension);
            if (extension != null) {
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }
            return type;
        }
    }

    /**
     * 选择文件及拍照
     */
    private Intent gotoChooseFile() {
        String saveName = Environment.getExternalStorageDirectory().getPath() + "/Movie/Camera/";
        File dir = new File(saveName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        mCameraPhotoPath = null;
        /**
         * 打开相机intent
         */
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
            photoFile = null;
            photoFile = new File(saveName + randomFileName() + ".jpg");
            if (!photoFile.exists()) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
//                    Uri imageUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID, new File(saveName));
//                    takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                } else {
                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));  // 把Uri赋值给takePictureIntent
//                }

            } else {
                takePictureIntent = null;
            }
        }

        Intent[] takeoutArray = null;
        if (takePictureIntent != null) {
            takeoutArray = new Intent[]{takePictureIntent};
        } else {
            takeoutArray = new Intent[0];
        }

        /**
         * 获取图片intent
         */
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        /**
         * 使用系统选择器
         */
        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, takeoutArray);  // 额外的intent
        }
        return chooserIntent;
    }

    /**
     * 随机产生文件名
     */
    private String randomFileName() {
        return UUID.randomUUID().toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOLIPOP) {  // 选择文件返回 5.0+
            Uri[] results = null;
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    if (mCameraPhotoPath != null) {
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
//                    else {
//                        if (photoFile != null) {
//                            Uri imageUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID, photoFile);
//                            results = new Uri[]{imageUri};
//                        }
//                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }
            mFilePathCallback.onReceiveValue(results);  // 当获取要传图片的Uri，通过该方法回调通知
            mFilePathCallback = null;
        }
    }

}
